package view
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class PrviewArea extends Sprite
	{
		private var _width:Number=CutPhotoConfig.scaleW;
		private var _height:Number=CutPhotoConfig.scaleH;
		
		private var _bd:BitmapData;
		private var _bm:Bitmap;
		private var _data:BitmapData;
		
		public function PrviewArea()
		{
			super();
			_width=CutPhotoConfig.scaleW;
			_height=CutPhotoConfig.scaleH;
			if(_width>210)
			{
				_width=210;
				_height=_height*210/CutPhotoConfig.scaleW;
			}
			if(_height>210)
			{
				var scale:Number=210/_height;
				_height*=scale;
				_width*=scale;
			}
			var g:Graphics=this.graphics;
			g.lineStyle(1,0xcccccc);
			g.beginFill(0xeeeeee);
			g.drawRect(-1,-1,_width+2,_height+2);
			g.endFill();
			_bm=new Bitmap;
			addChild(_bm);
		}
		public function load(l:Loader,r:Rectangle):void
		{
			if(!l||r.width<1||r.height<1)
			{
				return;
			}
			if(_bd)
			{
				_bd.dispose();
				_bd=null;
			}
			var scaleNum:Number=.5;
//			r.x=scaleNum*r.x;
//			r.y=scaleNum*r.y;
			r.width=scaleNum*r.width;
			r.height=scaleNum*r.height;
			_bm.scaleX=_bm.scaleY=1;
			_data=new BitmapData(r.width,r.height);
			var m:Matrix=new Matrix;
			m.translate(-r.x,-r.y);
			m.scale(scaleNum,scaleNum);
			_data.draw(l,m,null,null,null,true);
			_bm.bitmapData=_data;
			
			var scale:Number;
			if(r.width>width&&r.height>height)
			{
				scale=r.width/width>r.height/height?width/r.width:height/r.height;
			}
			else if(r.width<=width&&r.height>=height)
			{
				scale=height/r.height;
			}
			else if(r.width>=width&&r.height<=height)
			{
				scale=width/r.width;
			}
			else if(r.width<=width&&r.height<=height){
				scale=1;
			}
			_bm.scaleX=_bm.scaleY=scale;
			_bm.x=(width-_bm.width)*.5;
			_bm.y=(height-_bm.height)*.5;
			addChild(_bm);
		 	if(scale==1)
			{
				if(_bm.width<width)
				{
					_bm.width=width;
					_bm.x=0;
				}
				if(_bm.height<height)
				{
					_bm.height=height;
					_bm.y=0;
				}
			}
		}
		
		public function get data():BitmapData
		{
			return _data;
		}
		public override function get width():Number
		{
			return _width;
		}
		public override function get height():Number
		{
			return _height;
		}


	}
}